﻿/**************************************************************************
创建日期:	2019/7/22 11:19:22     
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com
创建时间:	
Copyright (c)  ZhCun.cn

描	述：
记	录：
***************************************************************************/
using System.Collections.Generic;
using ZhCun.DbCore.Cores;
using ZhCun.DBModel;
using ZhCun.RightsManage.DBModel;
using ZhCun.Utils.Helpers;
using ZhCun.WebUtils.DB;
using ZhCun.WebUtils.VModel;

namespace ZhCun.RightsManage.AL
{
    public class UserManageBLL : BLLCrudBase<ArgGetList, Sys_User>
    {
        protected override bool CheckSaveArg(Sys_User model, bool isAdd, out string msg)
        {
            if (StringHelper.IsNullOrWhiteSpace(model.LoginName, model.UserName, model.RoleId))
            {
                msg = "必要字段不能为空。";
                return false;
            }
            if (DB.QueryExist<Sys_User>(s => s.LoginName == model.LoginName && s.Id != model.Id))
            {
                msg = "登录名已存在";
                return false;
            }



            if (DB.QueryExist<Sys_User>(s => s.UserName == model.UserName && s.Id != model.Id))
            {
                msg = "用户名已存在";
                return false;
            }
            model.ClearChangedState();

            model.SetFieldChanged(
                Sys_User.CNUserName,
                Sys_User.CNLoginName,
                Sys_User.CNMobileNumber,
                Sys_User.CNIsManage,
                Sys_User.CNRoleId
                );
            //if (model.Id != AppCommonConfig.AppSettings.ManageUserId)
            //{
            //    //管理员不能修改角色
            //    model.SetFieldChanged(TSysUser.CNRoleId);
            //}
            if (isAdd)
            {
                model.LoginPwd = "112233";
            }
            msg = null;
            return true;
        }

        protected override ExecResult GetDelResult(string id)
        {
            return DB.Delete<Sys_User>(s => s.Id == id && s.RoleId != "000");
        }

        protected override void SetQueryOption(ArgGetList arg, QueryCondition<Sys_User> query)
        {
            query.OrderBy(s => s.AddTime);
            if (!string.IsNullOrWhiteSpace(arg.searchValue))
            {
                var likeStr = $"%{arg.searchValue}%";
                query.WhereAnd(s =>
                    s.WEx_Like(s.UserName, likeStr) ||
                    s.WEx_Like(s.LoginName, likeStr)
                );
            }
        }

        public List<Sys_Role> GetRoleList()
        {
            var query = DB.CreateQuery<Sys_Role>();
            query.OrderBy(s => s.AddTime);
            var r = DB.Query<Sys_Role>(query).ToList(true);
            return r;
        }
    }
}